<?php

/**
 * Proxy between jfJQMAmobeeAds Javascript and Amobee Ad Server
 * 
 * @package     jfJQMAmobeeAdsPlugin
 * @subpackage  lib
 * @author      Jonas Fischer <info@jonasfischer.net>
 * @version     SVN: $Id: BaseActions.class.php 12534 2008-11-01 13:38:27Z Kris.Wallsmith $
 */
class jfJQMAmobeeAdsProxy {

	private $adRequestIdAutoincrementValue = 1;

	protected $webserviceUrl = 'http://vfdeprod.amobee.com/upsteed/wap/adrequestm';
	protected $requestXmlTemplate = '<adrequestpacket responsemarkup="%responsemarkup%" test="0" xmlns="http://www.amobee.com/BatchWapSchema"></adrequestpacket>';
	
  public function execute() {
    $requestXml = $this->getDoc()->saveXML();
   	$resultXml = $this->postRequest($this->webserviceUrl, $requestXml);
   	
//    	echo $requestXml;
//    	echo "\n\n\n\n\n\n\n\n\n";
//    	echo $resultXml->asXML();
//    	die();
   	
    $result = array('status' => 200, 'content' => $resultXml->asXML());
    return $this->getRequestParameter('callback').'('.json_encode($result).')';
  }
  
  protected function getAdRequestIdAutoincrementValueAndIncrement() {
  	return $this->adRequestIdAutoincrementValue++;
  }
  
  protected function addAdRequestsToDoc($doc) {
  	foreach ($this->getRequestParameter('ads') as $position => $params) {
  		$this->addAdRequestToDoc($doc, $position+1, $params);
  	}
  }

  protected function addAdRequestToDoc($doc, $position, $params) {
  	$adRequest = $doc->createElement('adrequest');
  	$adRequest->setAttribute('adspace', $params['adspace']);
  	$adRequest->setAttribute('id', $this->getAdRequestIdAutoincrementValueAndIncrement());
  	$this->addParamToElement($doc, $adRequest, 'placement', $position);
  	//$this->addParamToElement($doc, $adRequest, 'time', intval((microtime(true)*1000)));
  	$this->addElementToDoc($doc, $adRequest);
  }
  
  protected function addUserInfoToDoc($doc) {
  	$userInfo = $doc->createElement('userinfo');
  	if (!empty($_SERVER['HTTP_USER_AGENT'])) {
  		$this->addParamToElement($doc, $userInfo, 'user-agent', $_SERVER['HTTP_USER_AGENT']);
  	}
  	
  	if (!empty($_SERVER['REMOTE_ADDR'])) {
  		$this->addParamToElement($doc, $userInfo, 'ira', $_SERVER['REMOTE_ADDR']);
  	}
  	
 		$this->addParamToElement($doc, $userInfo, 'userid', $this->getRequestParameter('userid'));
  	
  	$this->addElementToDoc($doc, $userInfo);
  }

  
  protected function addParamToElement($doc, $element, $name, $value) {
  	$param = $doc->createElement('param', $value);
 		$param->setAttribute('name', $name);
  	$element->appendChild($param);
  }
  
  protected function addElementToDoc($doc, $element) {
  	$doc->getElementsByTagName('adrequestpacket')->item(0)->appendChild($element);
  }
  
  protected function getDoc() {
  	$doc = $this->getBaseDoc();
  	$this->addUserInfoToDoc($doc);
  	$this->addAdRequestsToDoc($doc);
  	return $doc;
  }
  
  protected function getBaseDoc() {
		$doc = new DOMDocument;
		$xmlTemplate = $this->requestXmlTemplate;
		$xmlTemplate = str_replace('%responsemarkup%', $this->getRequestParameter('responsemarkup', 'xhtml'), $xmlTemplate);
    $doc->loadXML($xmlTemplate);
    
    return $doc;
  }
  
  private function getRequestParameter($key, $default = null) {
  	return $this->hasRequestParameter($key) ? $_REQUEST[$key] : $default;
  }
  
  private function hasRequestParameter($key) {
  	return array_key_exists($key, $_REQUEST);
  }
  
  private function postRequest($url, $data) {
  	$ch = curl_init();
		curl_setopt($ch, CURLOPT_HTTPHEADER, Array("Content-Type: text/xml; charset=utf-8")); 
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ch, CURLOPT_POST, 1);
		curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 20);
		curl_setopt($ch, CURLOPT_TIMEOUT, 40);	
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
		
		$content = curl_exec($ch);
		$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
		
		if ($httpCode == 200) {
			return simplexml_load_string($content);
		}
		else {
			throw new jfJQMAmobeeAdsException($content, $httpCode);
		}
  }
 
}
